package com.linln.admin.config;


import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

public class SmsUtils {

    private static final String EPID = "AHAQ1184115";
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "b2dbba5a5fbe68cc";

    private static final String SMS_URL = "http://access.xx95.net:8886/Connect_Service.asmx/SendSms";


    public static String sendSms(String phone,String content) {
        String s = "";
        try {
            RestTemplate restTemplate = new RestTemplate();

            // 转换参数为 MultiValueMap 格式
            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("epid", EPID);
            formData.add("User_Name", USER_NAME);
            formData.add("password", PASSWORD);
            formData.add("phone", phone);
            formData.add("content", content);
            // 构建请求实体
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, null);

            // 发送请求并返回结果
            ResponseEntity<String> response = restTemplate.postForEntity(SMS_URL, requestEntity, String.class);
            String resp = response.getBody();
            s = parseXml(resp);
        } catch (Exception e) {
            return "发送失败";
        }
        String msg = "";
        if (s.equals("00")){
            msg = "发送成功";
        }else{
            msg = "发送失败:"+s;
        }
        return msg;
    }

    public static String parseXml(String xmlString) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xmlString)));

        return document.getDocumentElement().getTextContent();
    }

}
